<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <title>Document</title>
    <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
    <script src="./js/store.legacy.min.js"></script>
</head>

<body>
    <img id="img1" src="./images/default.gif">
    <img id="img2" src="./images/default.gif">
    <script type="text/javascript">
    /**
     * [oImg1 基于localStroge的图片缓存]
     * @type {Image}
     */
    var oImg1 = new Image();
    var src = './images/1.jpg';
    var isCache = false;

    //获取缓存数据
    var oCaches = store.get('imgCache');

    //检查是否已经缓存
    for (key in oCaches) {
        if (src == key) {
            isCache = true;
        }
    }

    //判断是否已经缓存
    if (!isCache) {
        loadImg();
    } else {
        cacheImg()
    }

    //读取缓存图片
    function cacheImg() {
        selectId('#img1').setAttribute('src', oCaches[src]);
    }

    //请求图片
    function loadImg() {
        oImg1.src = src;
        oImg1.onload = function() {

            selectId('#img1').setAttribute('src', './images/1.jpg');
            var oBs = getBase64Image(oImg1);

            store.set('imgCache', {
                "./images/1.jpg": oBs
            });
            console.log('图片加载完成！');
        };
    };

    //ID选择器
    function selectId(str) {
        return document.querySelector(str);
    }

    //转码
    function getBase64Image(img) {
        var canvas = document.createElement("canvas");
        canvas.width = img.width;
        canvas.height = img.height;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0, img.width, img.height);
        var dataURL = canvas.toDataURL("image/jpg");
        return dataURL
    }
    </script>
</body>

</html>
